<template>
    <div>
        <div class="outdiv biaoti">管理员管理</div>
        <hr style="height:1px;border: none;border-top:1px solid #ddd;margin:15px 0;">
        <div class="tab outdiv">
            <el-button icon="el-icon-plus" class="addbtn" type="add" @click="addData">添加管理员</el-button>
            <el-table :data="tableData" height="350" border style="width: 100%">
                <el-table-column prop="userName" label="管理员账号">
                </el-table-column>
                <el-table-column prop="userLastTime" label="上次登陆时间">
                </el-table-column>
                <el-table-column prop="userEmail" label="邮箱">
                </el-table-column>
                <el-table-column prop="userPhone" label="电话号码">
                </el-table-column>
                <el-table-column prop="user_status" label="是否可用">
                    <template slot-scope="scope">
                        <el-switch @change="changeSwitch($event,scope.row)" v-model="scope.row.user_status"
                            active-text="可用" inactive-text="不可用" :active-value="1" :inactive-value="0"
                            active-color="#13ce66"></el-switch>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="180">
                    <template slot-scope="scope">
                        <el-button plain size="small" circle class="el-icon-edit" type="primary"
                            @click="handleEdit(scope.row)">
                        </el-button>
                        <!-- 删除按钮 -->

                        <el-popconfirm @onConfirm="handleDelete(scope.row)" title="确定删除这条信息吗？">
                            <el-button style="margin-left:10px;" plain slot="reference" size="small" type="danger"
                                circle icon="el-icon-delete">
                            </el-button>
                        </el-popconfirm>
                    </template>
                </el-table-column>
            </el-table>
        </div>


        <!-- 弹框 -->
        <el-dialog title="修改管理员信息" :visible.sync="dialogFormVisible">
            <el-form :model="form">
                <el-form-item label="用户名">
                    <el-input ref="myname" v-model="form.userName"></el-input>
                </el-form-item>
                <!--                <el-form-item label="密码">-->
                <!--                    <el-input show-password v-model="form.pwd"></el-input>-->
                <!--                </el-form-item>-->
                <el-form-item label="邮箱">
                    <el-input ref="myemail" v-model="form.email"></el-input>
                </el-form-item>
                <el-form-item label="电话号码">
                    <el-input ref="myphone" v-model="form.telpno"></el-input>
                </el-form-item>
                <el-checkbox-group ref="myquanxian" v-model="checkes">
                    <el-checkbox v-for="(item,index) in quanxian" :key="item" :label="index+1">{{item}}</el-checkbox>
                </el-checkbox-group>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="xiugaiDataOk">确 定</el-button>
            </div>
        </el-dialog>

        <!-- 弹框 -->
        <el-dialog title="添加管理员信息" :visible.sync="adddialogFormVisible">
            <el-form :rules='rules' :model="addform" ref="addform">
                <el-form-item label="用户名" prop="userName">
                    <el-input ref="username" @blur="checkUsername" v-model="addform.userName"></el-input>
                </el-form-item>
                <el-form-item prop="pwd" label="密码">
                    <el-input v-model="addform.pwd"></el-input>
                </el-form-item>
                <el-form-item prop="email" label="邮箱">
                    <el-input ref="useremail" @blur="checkUseremail" v-model="addform.email"></el-input>
                </el-form-item>
                <el-form-item prop="telpno" label="电话号码">
                    <el-input ref="userphone" @blur="checkUserphone" v-model="addform.telpno"></el-input>
                </el-form-item>
                <el-form-item label="管理权限">
                    <el-checkbox-group v-model="addcheckes">
                        <el-checkbox v-for="(item,index) in quanxian" :key="item" :label="index+1">{{item}}
                        </el-checkbox>
                    </el-checkbox-group>
                </el-form-item>
                <el-form-item>
                    <el-button @click="adddialogFormVisible = false">取 消</el-button>
                    <el-button type="primary" @click="addDataOk('addform')">确 定</el-button>
                </el-form-item>
            </el-form>
            <!-- <div slot="footer" class="dialog-footer">
                <el-button @click="adddialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="addDataOk">确 定</el-button>
            </div> -->
        </el-dialog>
    </div>
</template>

<script>
    import * as api from '../../utils/api'
    import {
        isvalidPhone
    } from '../../utils/validate'
    //定义一个全局的变量，谁用谁知道
    var validPhone = (rule, value, callback) => {
        if (!value) {
            callback(new Error('请输入电话号码'))
        } else if (!isvalidPhone(value)) {
            callback(new Error('请输入正确的11位手机号码'))
        } else {
            callback()
        }
    }
    export default {
        name: 'rightsMng',
        data() {
            return {
                tableData: [],
                dialogFormVisible: false,
                adddialogFormVisible: false,
                form: {
                    id: '',
                    userName: '',
                    pwd: '',
                    email: '',
                    telpno: '',
                    // station: ''
                },
                addform: {
                    id: '',
                    userName: '',
                    pwd: '',
                    email: '',
                    telpno: '',
                    // station: ''
                },
                otheruser: [],
                /* 选择的权限编号 */
                checkes: [],
                addcheckes: [],
                quanxian: ['订单管理', '客户管理', '优惠券管理', '内容管理', '保险管理', '评价管理', '退款'],
                rules: {
                    userName: [{
                            required: true,
                            message: '请输入用户名称',
                            trigger: 'blur'
                        },
                        {
                            min: 2,
                            max: 5,
                            message: '请限制在2-5个字符之间',
                            trigger: 'blur'
                        }
                    ],
                    pwd: [{
                        required: true,
                        message: '请输入密码',
                        trigger: 'blur'
                    }, {
                        min: 6,
                        max: 15,
                        message: '请限制在6-15个字符之间',
                        trigger: 'blur'
                    }],
                    email: [{
                        required: true,
                        message: '请输入您的邮箱',
                        trigger: 'blur'
                    }, {
                        type: 'email',
                        message: '请输入正确的邮箱地址:xxx@xxx',
                        trigger: ['blur', 'change']
                    }],
                    telpno: [{
                        required: true,
                        trigger: 'blur',
                        /* 自定义验证 */
                        validator: validPhone
                    }],
                }

            }
        },
        created() {
            this.getData()
        },
        methods: {
            getData() {
                this.axios({
                    url: api.GET_QUERYADMIN,
                    method: 'get',
                    params: {}
                }).then(data => {
                    this.tableData = data.data.data
                })
            },
            /* 失焦事件  核对账户名，邮箱，电话号码是否与其他人相同 */
            checkUsername() {
                this.$nextTick(function () {
                    this.axios({
                        url: api.GET_VERIFICATIONUSERNAME,
                        method: 'get',
                        params: {
                            userName: this.$refs.username.value,
                        }
                    }).then(data => {
                        if (data.data.code == 500) {
                            this.addform.userName = ''
                            this.$message({
                                message: '用户名重复，试试其他的呢~',
                                type: 'warning'
                            });
                        }
                    })
                })
            },

            checkUserphone() {
                this.$nextTick(function () {
                    this.axios({
                        url: api.GET_VERIFICATIONUSERPHONE,
                        method: 'get',
                        params: {
                            userPhone: this.$refs.userphone.value,
                        }
                    }).then(data => {
                        // console.log(data)
                        if (data.data.code == 500) {
                            this.addform.telpno = ''
                            this.$message({
                                message: '你的号码已经使用过了~',
                                type: 'warning'
                            });
                        }
                    })
                })
            },

            checkUseremail() {
                this.$nextTick(function () {
                    this.axios({
                        url: api.GET_VERIFICATIONUSEREMAIL,
                        method: 'get',
                        params: {
                            userEmail: this.$refs.useremail.value,
                        }
                    }).then(data => {
                        // console.log(data)
                        if (data.data.code == 500) {
                            this.addform.email = ''
                            this.$message({
                                message: '你的邮箱使用过了~',
                                type: 'warning'
                            });
                        }
                    })
                })
            },

            /* 修改状态 */
            changeSwitch(val, row) {
                this.axios({
                    url: api.GET_EDITAUTHORITYSTATU,
                    method: 'get',
                    params: {
                        userId: row.userId,
                        userStatu: val
                    }
                }).then(data => {
                    if (data.data.code === 200) {
                        this.$message({
                            message: '修改成功！',
                            type: 'success'
                        });
                        this.getData()
                    } else {
                        this.$message.error('修改失败！')
                    }
                })
            },
            /* 添加按钮 */
            addData() {
                if (this.$refs.addform !== undefined) {
                    this.$refs.addform.resetFields();
                }
                this.adddialogFormVisible = true
                this.addcheckes = []
            },
            /* 添加管理员数据 */
            addDataOk(formName) {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        this.axios({
                            url: api.POST_ADDAUTHORITY,
                            method: 'post',
                            data: {
                                permissions: this.addcheckes,
                                userEmail: this.addform.email,
                                // userId: this.addform.id,
                                userName: this.addform.userName,
                                userPhone: this.addform.telpno,
                                userPwd: this.addform.pwd,
                            }
                        }).then(data => {
                            if (data.data.code === 200) {
                                this.$message({
                                    message: '添加信息成功！',
                                    type: 'success'
                                });
                                this.getData()
                            } else {
                                this.$message.error('添加信息失败！')
                            }
                        })
                        this.adddialogFormVisible = false
                    } else {
                        return false;
                    }
                });
            },

            /* 编辑按钮 */
            handleEdit(row) {
                this.form.id = row.userId
                this.form.userName = row.userName
                this.form.pwd = row.userPwd
                this.form.email = row.userEmail
                this.form.telpno = row.userPhone
                this.checkes = row.user_permissions
                this.dialogFormVisible = true
                this.axios({
                    url: '/city/updateverificationUserName.do',
                    method: 'get',
                    params: {
                        user_id: row.userId
                    }
                }).then(data => {
                    this.otheruser = data.data.data
                })

            },
            /* 修改管理员数据 */
            xiugaiDataOk() {
                this.$nextTick(function () {
                    let myname = this.$refs.myname.value
                    let myemail = this.$refs.myemail.value
                    let myphone = this.$refs.myphone.value
                    let myquanxian = this.$refs.myquanxian.value
                    let othername = this.otheruser.filter(function (item) {
                        if (item.user_name === myname) {
                            return item
                        }
                    })
                    let otherEmail = this.otheruser.filter(function (item) {
                        if (item.user_email === myemail) {
                            return item
                        }
                    })
                    let otherPhone = this.otheruser.filter(function (item) {
                        if (item.user_phone === myphone) {
                            return item
                        }
                    })
                    if (othername != '') {
                        this.$message({
                            message: '你的用户名重复了~',
                            type: 'warning'
                        });
                    }
                    if (otherEmail != '') {
                        this.$message({
                            message: '你的邮箱使用过了~',
                            type: 'warning'
                        });
                    }
                    if (otherPhone != '') {
                        this.$message({
                            message: '你的电话使用过了~',
                            type: 'warning'
                        });
                    }
                    if (myquanxian.length === 0) {
                        this.$message({
                            message: '至少得有一项权限~',
                            type: 'warning'
                        });
                    }
                    if (otherEmail == '' && otherPhone == '' && othername == '' && myquanxian.length > 0) {
                        // console.log(myquanxian)
                        this.axios({
                            url: api.POST_UPDATAAUTHORITY,
                            method: 'post',
                            data: {
                                permissions: this.checkes,
                                userEmail: this.form.email,
                                user_id: this.form.id,
                                userName: this.form.userName,
                                userPhone: this.form.telpno,
                                // userPwd: this.form.pwd
                            }
                        }).then(data => {
                            // console.log(data)
                            if (data.data.code === 200) {
                                this.$message({
                                    message: '修改信息成功！',
                                    type: 'success'
                                });
                                this.getData()
                            } else if (data.data.code === 500) {
                                this.$message({
                                    message: data.data.msg,
                                    type: 'warning'
                                });
                            } else {
                                this.$message.error('修改信息失败！')
                            }
                            this.dialogFormVisible = false
                        })
                    }
                })
            },
            /* 删除按钮 */
            handleDelete(row) {
                // console.log(row)
                if (row.user_status === 0) {
                    this.axios({
                        url: api.POST_DELETEAUTHORITY,
                        method: 'get',
                        params: {
                            userId: row.userId
                        }
                    }).then(data => {
                        if (data.data.code === 200) {
                            this.$message({
                                message: '删除成功！',
                                type: 'success'
                            });
                            this.getData()
                        } else {
                            this.$message.error('删除失败！')
                        }
                    })
                } else {
                    this.$message.error('该成员信息不可以删除！')
                }

            },
        },

    }
</script>

<style lang='less' scoped>
    h2 {
        padding: 2rem 0 2rem 3rem;
    }

    /deep/.el-table .cell {
        text-align: center;
    }

    /* 新增按钮 */
    .el-button--add:hover {
        color: rgb(240, 248, 255);
        background-color: rgb(148, 197, 238);
        border-color: rgb(148, 197, 238);
    }

    .el-button--add {
        color: rgb(148, 197, 238);
        background-color: rgb(240, 248, 255);
        border-color: rgb(148, 197, 238);
    }

    .addbtn {
        margin: 2rem;
    }

    .tab {
        padding: 0 4rem;
    }
</style>